package com.shadt.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

/**
 * 
 * @Title: XMLParser.java
 * @Description: xml转换帮助类
 * @author SongR
 * @date 2016-5-13 下午2:21:12
 * @version V1.0
 */
public class XMLParser {

	/**
	 * 对象转换成xml字符串
	 * @param obj
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getXmlFromObj(Object obj, Class clazz) {
		XStream xs = new XStream(new DomDriver("UTF-8",new XmlFriendlyNameCoder("-_", "_")));
		xs.alias("xml", clazz);
		return xs.toXML(obj);
	}

	/**
	 * 字符串转换成对象
	 * @param xml
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object getObjectFromXml(String xml,Class clazz) {
		XStream xs = new XStream(new DomDriver("UTF-8",new XmlFriendlyNameCoder("-_", "_")));
		xs.alias("xml", clazz);
		return xs.fromXML(xml);
	}

	/**
	 * 从RefunQueryResponseString里面解析出退款订单数据
	 * 
	 * @param refundQueryResponseString
	 *            RefundQuery API返回的数据
	 * @return 因为订单数据有可能是多个，所以返回一个列表
	 */

	public static Map<String, Object> getMapFromXML(String xmlString)
			throws ParserConfigurationException, IOException, SAXException {
		// 这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputStream is = XMLUtil.getStringStream(xmlString);
		Document document = builder.parse(is);

		// 获取到document里面的全部结点
		NodeList allNodes = document.getFirstChild().getChildNodes();
		Node node;
		Map<String, Object> map = new HashMap<String, Object>();
		int i = 0;
		while (i < allNodes.getLength()) {
			node = allNodes.item(i);
			if (node instanceof Element) {
				map.put(node.getNodeName(), node.getTextContent());
			}
			i++;
		}
		return map;

	}

	@SuppressWarnings("rawtypes")
	public static Object getObjectFromXML(String xml, Class tClass) {
		// 将从API返回的XML数据映射到Java对象
		XStream xStreamForResponseData = new XStream();
		xStreamForResponseData.alias("xml", tClass);
		// xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
		return xStreamForResponseData.fromXML(xml);
	}

}
